package com.framework.bdf4j.socket.coder;

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class MyEncoder extends MessageToByteEncoder {

    private Charset charset;

    public MyEncoder(Charset charset) {
        this.charset = charset;
    }



    private String setLength(String str) {
        // 完整报文：10位长度 + 报文内容
//        System.out.println(str+"<--00000000000000---");
        return String.format("%08d", str.getBytes(charset).length) + str;
    }

	@Override
	protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        out.writeBytes(setLength((String) msg).getBytes(charset));
		
	}

}

